using System;
using System.Collections.Generic;

using Kannon.Impl;

namespace Kannon.Core
{
    public abstract class KannonApplication : IKannonHandler
    {
        private readonly IList<RouteHandlerDescriptor> routeHandlers = new List<RouteHandlerDescriptor>();
        private IKannonHandler handler;

        public static IServiceProvider ServiceProvider
        { get; set; }

        public string ApplicationPath
        { get; set; }

        protected KannonApplication()
        {
            ServiceProvider = new ActivatorServiceProvider();

            handler = new KannonApplicationHandler(routeHandlers);
        }

        protected void Install<TMiddleware>()
        {
            var middleware = (KannonMiddleware)ServiceProvider.GetService(typeof(TMiddleware));
            middleware.AttachTo(handler);

            handler = middleware;
        }

        protected void Dispatch(string url, Func<KannonResponse> handler)
        {
            routeHandlers.Add(new RouteHandlerDescriptor(url, request => handler()));
        }

        public virtual KannonResponse Handle(KannonRequest request)
        {
            return handler.Handle(request);
        }

        protected virtual string GetApplicationRelativeUrl(string url)
        {
            return string.IsNullOrEmpty(ApplicationPath) ?
                url :
                ApplicationPath.TrimEnd('/') + "/" + url.TrimStart('/');
        }
    }
}